#include "GuiBuilder.h"

GuiBuilder::GuiBuilder() {}
GuiBuilder::~GuiBuilder() = default;

void GuiBuilder::done()
{
    main_ = nullptr;
    menubar_ = nullptr;
    menu_ = nullptr;
    toolbar_ = nullptr;
    gridLayout_ = nullptr;
    tabWidget_ = nullptr;
}

GuiBuilder& GuiBuilder::setMenuBar(QMenuBar* menubar)
{
    menubar_ = menubar;
    return *this;
}

GuiBuilder& GuiBuilder::addMenu(const QString& title, const QString& name)
{
    menu_ = new QMenu(menubar_);
    if (!name.isEmpty()) {
        menu_->setObjectName(name);
    }
    menu_->setTitle(title);
    menubar_->addAction(menu_->menuAction());
    return *this;
}

GuiBuilder& GuiBuilder::addMenuAction(QAction* action)
{
    menu_->addAction(action);
    return *this;
}

GuiBuilder& GuiBuilder::addMenuSeparator()
{
    menu_->addSeparator();
    return *this;
}

GuiBuilder& GuiBuilder::addToolBar(
    QWidget* parent,
    std::function<void(QToolBar*)> postAction
)
{
    toolbar_ = new QToolBar(parent);
    if (postAction) {
        postAction(toolbar_);
    }
    return *this;
}

GuiBuilder& GuiBuilder::setToolBar(QToolBar* toolbar)
{
    toolbar_ = toolbar;
    return *this;
}

GuiBuilder& GuiBuilder::addToolBarAction(QAction* action)
{
    toolbar_->addAction(action);
    return *this;
}

GuiBuilder& GuiBuilder::addToolBarAction(
    const QString& title,
    const QIcon& icon,
    std::function<void(QAction*)> postAction
)
{
    QAction* action = new QAction(title, toolbar_);
    action->setIcon(QIcon(":/icons/camera_redo.svg"));
    toolbar_->addAction(action);

    if (postAction) {
        postAction(action);
    }
    return *this;
}

GuiBuilder& GuiBuilder::addToolBarSeparator()
{
    toolbar_->addSeparator();
    return *this;
}

GuiBuilder& GuiBuilder::setGridLayout(QWidget* parent)
{
    gridLayout_ = new QGridLayout(parent);
    return *this;
}

GuiBuilder& GuiBuilder::setTabWidget(QTabWidget* tabWidget)
{
    tabWidget_ = tabWidget;
    return *this;
}

GuiBuilder& GuiBuilder::addTabWidget(std::function<void(QTabWidget*)> postAction
)
{
    tabWidget_ = new QTabWidget(gridLayout_->parentWidget());
    tabWidget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    gridLayout_->addWidget(tabWidget_, 0, 0);

    if (postAction) {
        postAction(tabWidget_);
    }
    return *this;
}
GuiBuilder& GuiBuilder::addTab(QWidget* widget, const QString& title)
{
    QWidget* tab = new QWidget(tabWidget_);
    tabWidget_->addTab(tab, title);

    QGridLayout* layout = new QGridLayout(tab);
    layout->addWidget(widget, 0, 0);

    return *this;
}

GuiBuilder& GuiBuilder::addDock(
    QWidget* widget,
    const QString title,
    Qt::DockWidgetArea area
)
{
    QDockWidget* dock = new QDockWidget(main_);
    dock->setMinimumWidth(360);
    dock->setWindowTitle(title);
    dock->setWidget(widget);

    main_->addDockWidget(area, dock);
    return *this;
}
